package com.phiture.erp.purchase.web.controller.admin;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.phiture.erp.basic.api.pojo.resp.ErpMaterialInfoResp;
import com.phiture.erp.basic.api.pojo.resp.ErpSupplierResp;
import com.phiture.erp.basic.api.service.ErpMaterialApi;
import com.phiture.erp.basic.api.service.ErpSupplierApi;
import com.phiture.erp.purchase.core.pojo.dto.ErpPurchaseOrderPageReqDTO;
import com.phiture.erp.purchase.core.pojo.dto.ErpPurchaseOrderSaveReqDTO;
import com.phiture.erp.purchase.core.pojo.vo.ErpPurchaseOrderRespVO;
import com.phiture.erp.purchase.core.pojo.vo.ErpPurchaseRequestItemPushVO;
import com.phiture.erp.purchase.core.service.ErpPurchaseOrderService;
import com.phiture.erp.purchase.core.service.ErpPurchaseRequestService;
import com.phiture.erp.purchase.dal.entity.ErpPurchaseOrderDO;
import com.phiture.erp.purchase.dal.entity.ErpPurchaseOrderItemDO;
import com.phiture.erp.purchase.dal.entity.ErpPurchaseRequestItemsDO;
import com.phiture.erp.stock.api.service.ErpStockApi;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMultiMap;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;

@Tag(name = "管理后台 - ERP 采购订单")
@RestController
@RequiredArgsConstructor
@RequestMapping("/erp/purchase-order")
public class ErpPurchaseOrderController {
    private final ErpPurchaseOrderService purchaseOrderService;
    private final ErpStockApi stockApi;
    private final ErpMaterialApi materialApi;
    private final ErpSupplierApi supplierApi;
    private final AdminUserApi adminUserApi;
    private final ErpPurchaseRequestService purchaseRequestService;

    @PostMapping("/create")
    @Operation(summary = "创建采购订单")
    @PreAuthorize("@ss.hasPermission('erp:purchase-order:create')")
    public CommonResult<Long> createPurchaseOrder(@Valid @RequestBody ErpPurchaseOrderSaveReqDTO createReqDTO) {
        return success(purchaseOrderService.createPurchaseOrder(createReqDTO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新采购订单")
    @PreAuthorize("@ss.hasPermission('erp:purchase-order:update')")
    public CommonResult<Boolean> updatePurchaseOrder(@Valid @RequestBody ErpPurchaseOrderSaveReqDTO updateReqDTO) {
        purchaseOrderService.updatePurchaseOrder(updateReqDTO);
        return success(true);
    }

    @PutMapping("/update-status")
    @Operation(summary = "更新采购订单的状态")
    @PreAuthorize("@ss.hasPermission('erp:purchase-order:update-status')")
    public CommonResult<Boolean> updatePurchaseOrderStatus(@RequestParam("id") Long id,
                                                      @RequestParam("status") Integer status) {
        purchaseOrderService.updatePurchaseOrderStatus(id, status);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除采购订单")
    @Parameter(name = "ids", description = "编号数组", required = true)
    @PreAuthorize("@ss.hasPermission('erp:purchase-order:delete')")
    public CommonResult<Boolean> deletePurchaseOrder(@RequestParam("ids") List<Long> ids) {
        purchaseOrderService.deletePurchaseOrder(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得采购订单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:purchase-order:query')")
    public CommonResult<ErpPurchaseOrderRespVO> getPurchaseOrder(@RequestParam("id") Long id) {
        ErpPurchaseOrderDO purchaseOrder = purchaseOrderService.getPurchaseOrder(id);
        if (purchaseOrder == null) {
            return success(null);
        }
        List<ErpPurchaseOrderItemDO> purchaseOrderItemList = purchaseOrderService.getPurchaseOrderItemListByOrderId(id);
        Map<Long, ErpMaterialInfoResp> materialMap = materialApi.getMaterialMap(
                convertSet(purchaseOrderItemList, ErpPurchaseOrderItemDO::getMaterialId));
        return success(cn.iocoder.yudao.framework.common.util.object.BeanUtils.toBean(purchaseOrder, ErpPurchaseOrderRespVO.class, purchaseOrderVO ->
                purchaseOrderVO.setItems(cn.iocoder.yudao.framework.common.util.object.BeanUtils.toBean(purchaseOrderItemList, ErpPurchaseOrderRespVO.Item.class, item -> {
                    BigDecimal purchaseCount = stockApi.getStockCount(item.getMaterialId());
                    item.setStockCount(purchaseCount != null ? purchaseCount : BigDecimal.ZERO);
                    MapUtils.findAndThen(materialMap, item.getMaterialId(), material -> item.setMaterialName(material.getName())
                            .setMaterialBarCode(material.getBarCode()).setMaterialUnitName(material.getUnitName()));
                }))));
    }

    @GetMapping("/getByPurNo")
    @Operation(summary = "获得采购订单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:purchase-order:query')")
    public CommonResult<ErpPurchaseOrderRespVO> getPurchaseOrderByPurNo(@RequestParam("purNo") String purNo) {
        ErpPurchaseOrderDO purchaseOrder = purchaseOrderService.getPurchaseOrderByPurNo(purNo);
        if (purchaseOrder == null) {
            return success(null);
        }
        List<ErpPurchaseOrderItemDO> purchaseOrderItemList = purchaseOrderService.getPurchaseOrderItemListByOrderIdForPurIn(purchaseOrder.getId());
        Map<Long, ErpMaterialInfoResp> materialMap = materialApi.getMaterialMap(
                convertSet(purchaseOrderItemList, ErpPurchaseOrderItemDO::getMaterialId));
        return success(cn.iocoder.yudao.framework.common.util.object.BeanUtils.toBean(purchaseOrder, ErpPurchaseOrderRespVO.class, purchaseOrderVO ->
                purchaseOrderVO.setItems(cn.iocoder.yudao.framework.common.util.object.BeanUtils.toBean(purchaseOrderItemList, ErpPurchaseOrderRespVO.Item.class, item -> {
                    BigDecimal purchaseCount = stockApi.getStockCount(item.getMaterialId());
                    item.setStockCount(purchaseCount != null ? purchaseCount : BigDecimal.ZERO);
                    MapUtils.findAndThen(materialMap, item.getMaterialId(), material -> item.setMaterialName(material.getName())
                            .setMaterialBarCode(material.getBarCode()).setMaterialUnitName(material.getUnitName()));
                }))));
    }

    // TODO 下推采购订单的时候，物料的供应商相同的在一个采购订单中
    @GetMapping("/page")
    @Operation(summary = "获得采购订单分页")
    @PreAuthorize("@ss.hasPermission('erp:purchase-order:query')")
    public CommonResult<PageResult<ErpPurchaseOrderRespVO>> getPurchaseOrderPage(@Valid ErpPurchaseOrderPageReqDTO pageReqDTO) {
        PageResult<ErpPurchaseOrderDO> pageResult = purchaseOrderService.getPurchaseOrderPage(pageReqDTO);
        return success(buildPurchaseOrderVOPageResult(pageResult));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出采购订单 Excel")
    @PreAuthorize("@ss.hasPermission('erp:purchase-order:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportPurchaseOrderExcel(@Valid ErpPurchaseOrderPageReqDTO pageReqDTO,
                                    HttpServletResponse response) throws IOException {
        pageReqDTO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ErpPurchaseOrderRespVO> list = buildPurchaseOrderVOPageResult(purchaseOrderService.getPurchaseOrderPage(pageReqDTO)).getList();
        // 导出 Excel
        ExcelUtils.write(response, "采购订单.xls", "数据", ErpPurchaseOrderRespVO.class, list);
    }

    private PageResult<ErpPurchaseOrderRespVO> buildPurchaseOrderVOPageResult(PageResult<ErpPurchaseOrderDO> pageResult) {
        if (CollUtil.isEmpty(pageResult.getList())) {
            return PageResult.empty(pageResult.getTotal());
        }
        // 1.1 订单项
        List<ErpPurchaseOrderItemDO> purchaseOrderItemList = purchaseOrderService.getPurchaseOrderItemListByOrderIds(
                convertSet(pageResult.getList(), ErpPurchaseOrderDO::getId));
        Map<Long, List<ErpPurchaseOrderItemDO>> purchaseOrderItemMap = convertMultiMap(purchaseOrderItemList, ErpPurchaseOrderItemDO::getOrderId);
        // 1.2 产品信息
        Map<Long, ErpMaterialInfoResp> materialMap = materialApi.getMaterialMap(
                convertSet(purchaseOrderItemList, ErpPurchaseOrderItemDO::getMaterialId));
        // 1.3 供应商信息
        Map<Long, ErpSupplierResp> supplierMap = supplierApi.getSupplierMap(
                convertSet(pageResult.getList(), ErpPurchaseOrderDO::getSupplierId));
        // 1.4 管理员信息
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(
                convertSet(pageResult.getList(), purchaseOrder -> Long.parseLong(purchaseOrder.getCreator())));
        // 2. 开始拼接
        return cn.iocoder.yudao.framework.common.util.object.BeanUtils.toBean(pageResult, ErpPurchaseOrderRespVO.class, purchaseOrder -> {
            purchaseOrder.setItems(cn.iocoder.yudao.framework.common.util.object.BeanUtils.toBean(purchaseOrderItemMap.get(purchaseOrder.getId()), ErpPurchaseOrderRespVO.Item.class,
                    item -> MapUtils.findAndThen(materialMap, item.getMaterialId(), material -> item.setMaterialName(material.getName())
                            .setMaterialBarCode(material.getBarCode()).setMaterialUnitName(material.getUnitName()))));
            purchaseOrder.setMaterialNames(CollUtil.join(purchaseOrder.getItems(), "，", ErpPurchaseOrderRespVO.Item::getMaterialName));
            MapUtils.findAndThen(supplierMap, purchaseOrder.getSupplierId(), supplier -> purchaseOrder.setSupplierName(supplier.getName()));
            MapUtils.findAndThen(userMap, Long.parseLong(purchaseOrder.getCreator()), user -> purchaseOrder.setCreatorName(user.getNickname()));
        });
    }


    @PostMapping("/create-order-from-request")
    @Operation(summary = "创建采购订单", description = "根据采购申请单ID创建采购订单")
    @Parameter(name = "requestIds", description = "申请单IDS")
    @PreAuthorize("@ss.hasPermission('erp:purchase-request:query')")
    public CommonResult<List<ErpPurchaseOrderRespVO.Item>> getPurchaseRequestItemsListByRequestId(@RequestBody List<ErpPurchaseRequestItemPushVO> requestItems) {
        // 使用mybatis一次性查出所有的采购申请单明细
        List<ErpPurchaseRequestItemsDO> purchaseRequestItemsList = purchaseRequestService.getPurchaseRequestItemsListByRequestIds(requestItems);
        // 上述purchaseRequestItemsList转成ErpPurchaseOrderItemDO类型的列表，但是数量属性一个count,一个qty
        // 需要将count转成qty
        List<ErpPurchaseOrderItemDO> purchaseOrderItemList = new ArrayList<>();
        for (ErpPurchaseRequestItemsDO item : purchaseRequestItemsList) {
            ErpPurchaseOrderItemDO orderItem = new ErpPurchaseOrderItemDO();
            // 复制其他相同名称的属性, 其中id不复制
            BeanUtils.copyProperties(item, orderItem,"id");
            // 手动处理数量属性的映射
            orderItem.setCount(item.getQty().subtract(item.getPurchaseOrderQty() == null ? BigDecimal.ZERO : item.getPurchaseOrderQty()));
            orderItem.setTaxPercent(BigDecimal.valueOf(item.getTax() == null ? 0 : item.getTax()));
            orderItem.setSourceBillId(item.getRequestId());
            orderItem.setSourceBillDetailId(item.getId());
            orderItem.setDeliveryDate(item.getRequireDate());
            purchaseOrderItemList.add(orderItem);
        }
        // 物料信息
        Map<Long, ErpMaterialInfoResp> materialMap = materialApi.getMaterialMap(
                convertSet(purchaseOrderItemList, ErpPurchaseOrderItemDO::getMaterialId));

        // purchaseOrderItemList需要转成ErpPurchaseOrderRespVO.Item类型的列表
        List<ErpPurchaseOrderRespVO.Item> purchaseOrderItemRespList = cn.iocoder.yudao.framework.common.util.object.BeanUtils.toBean(purchaseOrderItemList, ErpPurchaseOrderRespVO.Item.class, item -> {
            MapUtils.findAndThen(materialMap, item.getMaterialId(), material -> item.setMaterialName(material.getName())
                    .setMaterialBarCode(material.getBarCode())
                    .setMaterialPrice(material.getPurchasePrice())
                    .setMaterialUnitName(material.getUnitName()));
        });

        return success(purchaseOrderItemRespList);

    }


}